import React, { useState, useEffect } from 'react';
import { downloadPoc } from '@api/task';
import { Button, message, Upload, Icon } from 'antd';
import _ from 'lodash';
import PropTypes from 'prop-types';
const PocUploader = ({ value, onChange }) => {
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    // uploadName 已上传的文件名称
    if (value && value.uploadName) {
      setFileList([value]);
    } else if (!value) {
      setFileList([]);
    }
  }, [value]);

  const beforeUpload = file => {
    const name = _.get(file, 'name');
    if (!/\.py$/.test(name)) {
      message.info('请上传".py"格式文件');
    } else {
      setFileList([file]);
      onChange(file);
    }
    return false;
  };
  const onRemove = e => {
    e.stopPropagation();
    setFileList([]);
    onChange('');
  };
  const handleDownload = () => {
    if (fileList[0].uploadName) {
      downloadPoc(fileList[0].uploadName);
    }
  };
  return (
    <div className={'poc-modal-upload'}>
      <Upload beforeUpload={beforeUpload} withCredentials showUploadList={false} accept=".py">
        <Button>点击上传.py文档</Button>
      </Upload>
      <a target={'_blank'} href={'/poc_rules.pdf'} style={{ marginLeft: 10 }}>
        下载POC编写文档规范
      </a>
      {Boolean(fileList.length) && (
        <div onClick={handleDownload} className={'file-box'}>
          <div>
            <Icon type="paper-clip" />
            {fileList[0].name || fileList[0].uploadName}
          </div>
          <Icon type="delete" onClick={onRemove} />
        </div>
      )}
    </div>
  );
};
PocUploader.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func
};
export default PocUploader;
